﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Resources;
using System.Windows.Markup;
using System.Windows.Controls.Theming;

namespace System.Windows
{
    /// <summary>
    /// Implements a helper class for applying <see cref="System.Windows.ResourceDictionary"/> based Themes to an element hierarchy
    /// </summary>
    public class Theme
    {
        private Theme()
        {
        }

        private static Theme        _Current = null;
        private ResourceDictionary  _Dictionary = null;

        /// <summary>
        /// Fires when the Theme has changed
        /// </summary>
        public event EventHandler   ThemeChanged = null;

        /// <summary>
        /// Gets the current <see cref="Theme"/> instance.
        /// </summary>
        public static Theme Current
        {
            get
            {
                if (_Current == null) _Current = new Theme();
                return _Current;
            }
        }

        /// <summary>
        /// Loads a <see cref="System.Windows.ResourceDictionary"/> as a theme to be applied to the Root Visual
        /// </summary>
        /// <param name="resourceUri"></param>
        public void LoadTheme(Uri resourceUri)
        {
            Uri uri = resourceUri ?? new Uri("System.Windows.Controls.Views.Tookit;component/Themes/generic.xaml", UriKind.Relative);

            if (Application.Current.RootVisual != null)
            {
                FrameworkElement rootElement = Application.Current.RootVisual as FrameworkElement;
                if (rootElement != null)
                {
                    Application.LoadComponent(rootElement.Resources, uri);
                    
                    //ImplicitStyleManager.SetResourceDictionaryUri(rootElement, uri);
                    //ImplicitStyleManager.SetApplyMode(rootElement, ImplicitStylesApplyMode.Auto);
                    //ImplicitStyleManager.Apply(rootElement);
                }
            }
            
            StreamResourceInfo streamInfo = Application.GetResourceStream(uri);

            using (StreamReader sr = new StreamReader(streamInfo.Stream))
            {
                string xaml = sr.ReadToEnd();

                _Dictionary = XamlReader.Load(xaml) as ResourceDictionary;
                if (_Dictionary != null)
                {
                    if (this.ThemeChanged != null) this.ThemeChanged(this, EventArgs.Empty);
                }
            }
        }
    }
}
